package com.seezoon.application.user.executor;

import com.seezoon.application.user.dto.SendResetPasswordCodeCmd;
import com.seezoon.domain.service.user.CaptchaService;
import com.seezoon.domain.service.user.vo.CaptchaVO;
import com.seezoon.domain.service.user.vo.UserRegisterTypeVO;
import com.seezoon.infrastructure.dto.Response;
import com.seezoon.infrastructure.error.ErrorCode;
import com.seezoon.infrastructure.properties.AppProperties;
import com.seezoon.infrastructure.security.TotpService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.nio.charset.StandardCharsets;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

/**
 * 发送重置密码验证码
 */
@RequiredArgsConstructor
@Slf4j
@Component
@Validated
public class SendResetPasswordCodeCmdExe {

    private final CaptchaService captchaService;
    private final TotpService totpService;
    private final AppProperties appProperties;

    public Response execute(@Valid @NotNull SendResetPasswordCodeCmd cmd) {
        UserRegisterTypeVO.check(cmd.getResetType());
        // 1、验证图形验证码
        boolean verify = captchaService.verify(cmd.getTarget(), CaptchaVO.TYPE_USER_RESET_PASSWORD,
                cmd.getCaptchaText(),
                cmd.getCaptchaToken());
        if (!verify) {
            return Response.error(ErrorCode.CAPTCHA_NOT_MATCH);
        }

        String secretKey = appProperties.getSecretKey() + cmd.getTarget();
        // 2、发送验证码
        String code = totpService.generateCode(secretKey.getBytes(StandardCharsets.UTF_8));
        if (cmd.getResetType() == UserRegisterTypeVO.MOBILE) {
            // TODO: 发送手机验证码
            log.info("send reset password mobile code to: {}, code: {}", cmd.getTarget(), code);
        } else if (cmd.getResetType() == UserRegisterTypeVO.EMAIL) {
            // TODO: 发送邮箱验证码
            log.info("send reset password email code to: {}, code: {}", cmd.getTarget(), code);
        } else {
            throw new IllegalStateException("user reset password type illegal");
        }
        return Response.success();
    }
} 